package vip.mtdp.asset.core.utils;

import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.util.Map;

/**
 * @Description
 * @Author Evans.wang
 * @since 2023/10/29 22:32
 **/
public class ExprUtil {

    private static SpelExpressionParser parser = new SpelExpressionParser();

    private static EvaluationContext context = new StandardEvaluationContext();


    /**
     * spring el表达式解析
     * @param expr
     * @param clazz
     * @return
     */
    public static <T> T parse(String expr, Object o, Class<T> clazz){
        context.setVariable("txn", o);
        Expression exp = parser.parseExpression(expr);
        return exp.getValue(context, clazz);
    }

    /**
     * spring el表达式解析
     * @param expr
     * @param clazz
     * @return
     */
    public static <T> T parse(String expr, Map<String, Object> data, Class<T> clazz){
        for (Map.Entry<String, Object> entry : data.entrySet()) {
            context.setVariable(entry.getKey(), entry.getValue());
        }
        Expression exp = parser.parseExpression(expr);
        return exp.getValue(context, clazz);
    }

}
